package com.lwl.concurrency.thread;

/**
 * <pre>
 * 线程实例的终端方法必interrupt()须配置配合线程终端判断逻辑
 * Thread.currentThread().isInterrupted()或者Thread.interrupted()
 * 使用,否则无效,相当于自己做了线程终端标志位
 *
 * 如果线程Thread.sleep过程中,调用了interrupt,将会抛出InterruptedException
 * </pre>
 *
 * @author liwenlong - 2018/3/25 16:21
 */
public class ThreadInterruptTest {

    public static void main(String[] args) throws InterruptedException {
        ThreadInterruptTest threadInterruptTest = new ThreadInterruptTest();
        //threadInterruptTest.test1();
        threadInterruptTest.test2();

    }

    /**<pre>
     * 如果线程Thread.sleep过程中,调用了interrupt,将会抛出InterruptedException
     * Thread.sleep()方法由于中断而抛出异常,此时,她会清楚中断标记,如果不处理,那么在下一次
     * 循环开始时,就无法捕获这个中断,所以在异常处理中,再次设置中断标志位.
     * 中断以后可能不希望程序继续执行,但是while(true)会循环执行,
     * 因此程序出现异常以后,应该设置中断标志,while不再执行
     * </pre>
     */
    public void test2() throws InterruptedException {
        Thread thread = new Thread() {
            @Override
            public void run() {
               while(true){
                   if (Thread.currentThread().isInterrupted()) {
                       System.out.println("currentThread isInterrupted");
                       return;
                   }
                   System.out.println("线程执行中...");
                   try {
                       Thread.sleep(2000);
                   } catch (InterruptedException e) {
                       System.out.println("线程在睡眠过程中被中断了");
                       Thread.currentThread().interrupt();
                       e.printStackTrace();
                   }
               }
            }
        };
        //启动线程
        thread.start();
        Thread.sleep(1500);
        //中断线程,相当于自己设置了线程终端标志位run,设置为false
        thread.interrupt();
    }

    /**
     * 线程interrupt终端测试
     *
     * @throws InterruptedException
     */
    public void test1() throws InterruptedException {
        Thread thread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        System.out.println("currentThread isInterrupted");
                        break;
                    }
                    Thread.yield(); //让出当前线程资源
                }
            }
        };
        //启动线程
        thread.start();
        Thread.sleep(2000);
        //中断线程,相当于自己设置了线程终端标志位run,设置为false
        thread.interrupt();
    }


}
